<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset="utf-8" />
    <title>layui</title>
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="stylesheet" th:href="@{/lib/layui-v2.6.3/css/layui.css}" media="all" />
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all" />
  </head>
  <body>
    <div class="layuimini-container">
      <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
          <legend>搜索信息</legend>
          <div style="margin: 10px 10px 10px 10px">
            <form class="layui-form layui-form-pane" action="">
              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">用户账号</label>
                  <div class="layui-input-inline">
                    <input type="text" name="userName" autocomplete="off" class="layui-input" />
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">用户昵称</label>
                  <div class="layui-input-inline">
                    <input type="text" name="nickName" autocomplete="off" class="layui-input" />
                  </div>
                </div>
                <div class="layui-inline">
                  <button
                    type="submit"
                    class="layui-btn layui-btn-primary"
                    lay-submit
                    lay-filter="data-search-btn"
                  >
                    <i class="layui-icon"></i> 搜 索
                  </button>
                </div>
              </div>
            </form>
          </div>
        </fieldset>
        <div class="layui-card">
          <div class="layui-card-header">动态操作</div>
          <div class="layui-card-body">
            <div class="layui-btn-container tag" lay-filter="demo" lay-allowclose="true"></div>
          </div>
        </div>
        <input type="hidden" id="deptId" />

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <button class="layui-btn layui-btn-normal" id="cancel">取消</button>
        <button class="layui-btn layui-btn-normal" id="submit">确认</button>
      </div>
    </div>

    <script type="text/html" id="role-dataScope">
      {{#if (d.dataScope == 1) { }}
      <span>全部数据</span>
      {{# }else if(d.dataScope == 2){ }}
      <span>自定义数据权限</span>
      {{# }else if(d.dataScope == 3){ }}
      <span>本部门数据权限</span>
      {{# }else if(d.dataScope == 4){ }}
      <span>本部门及以下数据权限</span>
      {{# } }}
    </script>
    <script id="role-status" type="text/html">
      <input type="checkbox" name="enable" value="{{d.roleId}}" lay-skin="switch" lay-text="启用|禁用"
      lay-filter="role-enable" {{ d.status == '1' ? 'checked' : '' }}>
    </script>

    <script th:src="@{/lib/layui-v2.6.3/layui.js}" charset="utf-8"></script>
    <script th:src="@{/js/lay-config.js?v=1.0.4}" charset="utf-8"></script>

    <script th:inline="none">
      const tableData = new Map();
      function test(roleIds, roleNames) {
        if (roleIds && roleNames) {
          let ids = roleIds.split(",");
          let names = roleNames.split(",");
          for (let [index, elem] of ids.entries()) {
            let obj = {};
            obj.roleId = parseInt(elem);
            obj.roleName = names[index];
            tableData.set(obj.roleId, obj);
          }
          console.log(tableData);
          init();
        }
      }
      layui.use(["tag", "form", "table"], function () {
        var $ = layui.jquery,
          form = layui.form,
          tag = layui.tag,
          table = layui.table;

        tag.render("demo", {
          skin: "layui-btn layui-btn-primary layui-btn-sm layui-btn-radius", //标签样式
          //tagText: '<i class="layui-icon layui-icon-add-1"></i>添加标签', //标签添加按钮提示文本
        });
        var active = {
          tagAdd: function (id, text) {
            //新增一个Tag项
            tag.add("demo", {
              text: text, //用于演示
              id: id, //实际使用一般是规定好的id，这里以时间戳模拟下
            });
          },
          tagDelete: function (id) {
            //删除指定Tag项
            tag.delete("demo", id); //删除：“商品管理”
          },
        };
        window.init = function () {
          for (let [k, v] of tableData) {
            active.tagAdd(k, v.roleName);
          }
          table.reload(
            "currentTableId",
            {
              page: {
                curr: 1,
              },
            },
            "data"
          );
        };

        tag.on("click(demo)", function (data) {
          console.log("点击");
          console.log(this); //当前Tag标签所在的原始DOM元素
          console.log(data.index); //得到当前Tag的所在下标
          console.log(data.elem); //得到当前的Tag大容器
        });

        tag.on("add(demo)", function (data) {
          console.log("新增");
          console.log(this); //当前Tag标签所在的原始DOM元素
          console.log(data.index); //得到当前Tag的所在下标
          console.log(data.elem); //得到当前的Tag大容器
          console.log(data.othis); //得到新增的DOM对象
          //return false; //返回false 取消新增操作； 同from表达提交事件。
        });

        tag.on("delete(demo)", function (data) {
          console.log("删除");
          console.log(this); //当前Tag标签所在的原始DOM元素
          console.log(data.index); //得到当前Tag的所在下标
          console.log(data.elem); //得到当前的Tag大容器
        });

        table.render({
          elem: "#currentTableId",
          url: "/sys-role/query",
          method: "post",
          contentType: "application/json",
          where: { id: "12344" },
          parseData: function (res) {
            // res 即为原始返回的数据
            console.log(res);
            return {
              code: res.code, // 解析接口状态
              msg: res.msg, // 解析提示文本
              count: res.data.totalCount, // 解析数据长度
              data: res.data.list, // 解析数据列表
            };
          },
          cols: [
            [
              { type: "checkbox", fixed: "left" },
              { field: "roleId", width: 80, title: "ID", sort: true },
              { field: "roleName", width: 120, title: "用户账号" },
              { field: "roleKey", width: 120, title: "角色编码", sort: true },
              { field: "roleSort", width: 120, align: "center", title: "显示顺序" },
              {
                field: "dataScope",
                width: 200,
                align: "center",
                templet: "#role-dataScope",
                title: "数据范围",
              },
              {
                field: "status",
                width: 200,
                align: "center",
                title: "部门状态",
                templet: "#role-status",
              },
            ],
          ],
          limits: [10, 15, 20, 25, 50, 100],
          limit: 10,
          page: true,
          request: {
            pageName: "pageNo", // 页码的参数名称，默认：page
            limitName: "pageSize", // 每页数据条数的参数名，默认：limit
          },
          skin: "line",
          done: function (res, curr, count) {
            let tableName = "currentTableId";

            for (var i = 0; i < res.data.length; i++) {
              if (tableData.has(res.data[i].roleId)) {
                res.data[i].LAY_CHECKED = true;
                var index = res.data[i]["LAY_TABLE_INDEX"];
                var checkbox = $("#" + tableName + "")
                  .next()
                  .find("tr[data-index=" + index + '] input[type="checkbox"]');
                checkbox.prop("checked", true).next().addClass("layui-form-checked");
                var radio = $("#" + tableName + "")
                  .next()
                  .find("tr[data-index=" + index + '] input[type="radio"]');
                radio.prop("checked", true).next().addClass("layui-form-radioed").find("i").html("&#xe643;");
              }
            }
            var checkStatus = table.checkStatus(tableName);
            if (checkStatus.isAll) {
              $("#" + tableName + "")
                .next()
                .find('.layui-table-header th[data-field="0"] input[type="checkbox"]')
                .prop("checked", true);
              $("#" + tableName + "")
                .next()
                .find('.layui-table-header th[data-field="0"] input[type="checkbox"]')
                .next()
                .addClass("layui-form-checked");
            }
          },
        });

        // 监听搜索操作
        form.on("submit(data-search-btn)", function (data) {
          //执行搜索重载
          table.reload(
            "currentTableId",
            {
              page: {
                curr: 1,
              },
              where: data.field,
            },
            "data"
          );

          return false;
        });

        //监听表格复选框选择
        table.on("checkbox(currentTableFilter)", function (obj) {
          console.log(obj);
          let data = obj.data;
          if (obj.checked) {
            //obj.type如果触发的是全选，则为：all，如果触发的是单选，则
            if (obj.type === "one") {
              if (!tableData.has(data.roleId)) {
                tableData.set(data.roleId, data);
                active.tagAdd(obj.data.roleId, obj.data.roleName);
              }
            } else {
              let datas = table.getData("currentTableId"); // 例如 let data = table.getData('Table-List');
              $.each(datas, function (idx, item) {
                if (!tableData.has(item.roleId)) {
                  tableData.set(item.roleId, item);
                  active.tagAdd(item.roleId, item.roleName);
                }
              });
            }
          } else {
            if (obj.type === "one") {
              //获取cc在数组中所在的下标
              if (tableData.has(data.roleId)) {
                tableData.delete(data.roleId);
                active.tagDelete(obj.data.roleId);
              }
            } else {
              let datas = table.getData("currentTableId"); // 例如 let data = table.getData('Table-List');
              $.each(datas, function (idx, item) {
                if (tableData.has(item.roleId)) {
                  tableData.delete(item.roleId);
                  active.tagDelete(item.roleId);
                }
              });
            }
          }
        });
        $("#cancel").click(function () {
          parent.layer.close(parent.layer.getFrameIndex(window.name));
        });
        $("#submit").click(function () {
          // 只能获取当前页的数据
          //var datas = table.checkStatus("currentTableId").data;
          console.log(tableData);

          let roleNames = [];
          let roleIds = [];
          for (let item of tableData.values()) {
            roleNames.push(item.roleName);
            roleIds.push(item.roleId);
          }
          parent.addDataAndRefresh($("#deptId").val(), roleNames.join(), roleIds.join());
          parent.layer.close(parent.layer.getFrameIndex(window.name));
        });
      });
    </script>
  </body>
</html>
